package snapex.core.controller;

import java.beans.PropertyEditorSupport;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@ControllerAdvice
public class DataBinderAdvice {
	
    @InitBinder
	public void initBinder(WebDataBinder binder) { 
		//set value to null for date field with blank value for HTTP request parameters
		binder.registerCustomEditor(java.sql.Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) throws IllegalArgumentException {
				if(StringUtils.isEmpty(text)) {
					this.setValue(null);
				}else {
					this.setValue(java.sql.Date.valueOf(text));
				}
			}
		});
		
		binder.registerCustomEditor(java.util.Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) throws IllegalArgumentException {
				if(StringUtils.isEmpty(text)) {
					this.setValue(null);
				}else {
					try {
						SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
						
						this.setValue(df.parse(text));
					}
					catch(Exception e) {
						log.error("",e);
						this.setValue(null);
					}
				}
			}
		});
		
		//trim leading and tailing space for HTTP request parameters
		binder.registerCustomEditor(String.class,new StringTrimmerEditor(true));
		
		binder.registerCustomEditor(java.math.BigDecimal.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) throws IllegalArgumentException {
				if(StringUtils.isEmpty(text)) {
					this.setValue(null);
				}else {
					try {						
						log.debug("**************text={}",text.replace(",", ""));
						
						this.setValue(new BigDecimal(text.replace(",", "")));
					}
					catch(Exception e) {
						log.error("",e);
						this.setValue(null);
					}
				}
			}
		});
	}
}
